<template>
  <el-dialog
    top="30px"
    width="800px"
    class="dialog-sm"
    append-to-body
    title="提前还款"
    :visible.sync="visible"
    :close-on-click-modal="false"
    :before-close="beforeClose"
  >
    <div class="d-flex">
      <div class="mr-5">
        <div class="accounting-progress" :class="`border-${statusStyle}`">
          <div class="font-weight-bold" :class="`text-${statusStyle}`">
            {{ enumPayStatus[editRow.payStatusReal] || '-' }}
          </div>
          <small class="text-muted">缴费状态</small>
        </div>

        <el-alert
          v-if="isViewMode && isUnionCity && editRow.payStatusReal > 9"
          style="width: 80px; padding: 8px 0; text-align: center"
          title="等待区县农担确认缴费"
          type="warning"
          :closable="false"
        ></el-alert>
      </div>
      <table class="table table-sm table-borderless accounting-table">
        <tbody>
          <tr>
            <td width="15%">项目名称：</td>
            <td width="35%">{{ editRow.customer_name || '-' }}</td>
            <td width="15%">贷款金额：</td>
            <td width="35%">{{ editRow.reply_funds || '-' }}万元</td>
          </tr>
          <tr>
            <td>项目负责人：</td>
            <td>{{ editRow.corp_name || '-' }}</td>
            <td>联系电话：</td>
            <td>{{ editRow.mobile_no || '-' }}</td>
          </tr>
          <tr>
            <td>起保时间：</td>
            <td>{{ $utils.dateFormat(editRow.load_date, 'yyyy年MM月dd日') || '-' }}</td>
            <td>结束时间：</td>
            <td>{{ $utils.dateFormat(editRow.load_end_date, 'yyyy年MM月dd日') || '-' }}</td>
          </tr>
          <tr>
            <td>项目地址：</td>
            <td>{{ editRow.address || '-' }}</td>
            <td>放款银行：</td>
            <td>{{ editRow.bank_name || '-' }}</td>
          </tr>
          <tr>
            <td>担保费率：</td>
            <td>{{ editRow.gua_rate || '-' }}%</td>
            <td>应缴时间：</td>
            <td>{{ dueWarrantDate }}</td>
          </tr>
          <template v-if="isViewMode">
            <template v-if="+editRow.actual_warrant_fee > 0">
              <tr>
                <td>还款金额：</td>
                <td colspan="3">{{ editRow.actual_warrant_fee || '-' }} 元</td>
              </tr>
              <tr>
                <td>情况说明：</td>
                <td colspan="3">{{ editRow.remark || '-' }}</td>
              </tr>
              <tr>
                <td>附件上传：</td>
                <td colspan="3">
                  <img-card :images="attachImages"></img-card>
                </td>
              </tr>
            </template>
            <template v-else>
              <tr>
                <td colspan="4">
                  <el-alert
                    title="提前还款"
                    type="success"
                    show-icon
                    class="mt-4"
                    :closable="false"
                  >
                    <span>已于 {{ actualWarrantDate }} 提前还款</span>
                  </el-alert>
                </td>
              </tr>
            </template>
          </template>
          <template v-else>
            <tr>
              <td>还款金额：</td>
              <td colspan="3">
                <el-input
                  size="small"
                  :min="0"
                  class="form-control-ml"
                  type="number"
                  v-model="warrantFee"
                  v-input-number="inputOptions"
                >
                  <template slot="append">元</template>
                </el-input>
              </td>
            </tr>
            <tr>
              <td>情况说明：</td>
              <td colspan="3">
                <el-input
                  size="small"
                  type="textarea"
                  class="form-control-ml"
                  v-model="remark"
                ></el-input>
              </td>
            </tr>
            <tr>
              <td>附件上传：</td>
              <td colspan="3">
                <upload-oss
                  multiple
                  accept="image/*"
                  listType="picture-card"
                  ref="attachOss"
                  :file-list="attachFileList"
                  :limit="10"
                  :on-complete="handleImagesComplete"
                ></upload-oss>
              </td>
            </tr>
          </template>

          <tr>
            <td></td>
            <td colspan="3" class="pt-5">
              <div v-if="!isViewMode" class="mb-1">
                <el-button
                  type="primary"
                  @click="handleConfirm"
                  :loading="saveLoading"
                  class="btn-long"
                >
                  确认提前还款
                </el-button>
                <el-button @click="handleDismiss" :loading="saveLoading" class="btn-long">
                  取消
                </el-button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { strip, arrayFromString } from '@vimi/utils-tool'
import { strFromOss } from '@/common/plugins/tools/format'

import { enumPayStatus, enumPayStatusStyle } from '@/credit/views/city/settle/settleMixins'

import ImgCard from '@/components/ImgCard'

export default {
  components: {
    ImgCard,
  },
  props: {
    visible: Boolean,
    editRow: {
      type: Object,
      default() {
        return {}
      },
    },
    viewMode: Boolean,
  },
  data() {
    return {
      enumPayStatus,
      attachFileList: [],
      warrantFee: '',
      remark: '',
      saveLoading: false,
      guaRate: '',
    }
  },
  computed: {
    ...mapGetters(['user']),
    isUserCity() {
      return this.user.orgRegionLever < 3
    },
    isUnionCity() {
      return +this.editRow.gua_type === 1 && this.isUserCity
    },
    statusStyle() {
      return enumPayStatusStyle[this.editRow.payStatusReal] || ''
    },
    isViewMode() {
      return this.viewMode || this.editRow.payStatusReal < 10
    },
    repayFunds() {
      return +this.editRow.reply_funds || 0
    },
    attachImages() {
      return this.attachFileList.map(item => item.url)
    },
    inputOptions() {
      return {
        min: 0,
        fixed: 4,
        onMin: () => this.$message.error('不能小于0'),
        onFixed: () => this.$message.error('小数点不能超过4位数'),
      }
    },
    dueWarrantDate() {
      return this.$utils.dateFormat(this.editRow.due_warrant_date, 'yyyy年MM月dd日') || '-'
    },
    actualWarrantDate() {
      return this.$utils.dateFormat(this.editRow.actual_warrant_date, 'yyyy年MM月dd日') || '-'
    },
  },
  watch: {
    editRow: {
      handler: function () {
        this.initForm()
      },
      immediate: true,
      deep: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    beforeClose() {
      this.$emit('update:visible', false)
    },
    initForm() {
      this.guaRate = +this.editRow.gua_rate || 0
      this.remark = this.editRow.remark || ''
      const funds = +this.editRow.left_funds || 0
      this.warrantFee = this.editRow.actual_warrant_fee || strip(this.guaRate * funds * 1e2) || ''
      this.attachFileList = arrayFromString(this.editRow.attachment).map(img => ({
        name: '',
        url: img,
      }))
    },
    handleConfirm() {
      if (!this.validate()) return
      this.saveLoading = true
      this.$refs.attachOss.submit()
    },
    handleDismiss() {
      this.beforeClose()
    },
    validate() {
      if (!this.warrantFee) {
        this.$message.error('请输入还款金额')
        return false
      }
      return true
    },
    handleImagesComplete(images) {
      this.saveLoading = false
      const imageStr = strFromOss(images)
      this.confirmEdit(imageStr)
    },
    confirmEdit(imageStr) {
      this.$confirm('确认提前还款?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
      })
        .then(() => {
          const formData = {
            pay_status: 3,
            attachment: imageStr,
            remark: this.remark,
            actual_warrant_fee: this.warrantFee,
            actual_warrant_date: this.$utils.dateFormat(new Date()),
          }
          this.updateData(formData)
        })
        .catch(() => {})
    },
    async updateData(data) {
      this.saveLoading = true
      const [res] = await this.$utils.promise(
        this.$api.updateData(this.$serviceName, 'credit_warrant_fee_record', this.editRow.id, data)
      )
      this.saveLoading = false

      if (!res) {
        return this.$message.error('提前还款失败，请重试')
      }

      this.$message.success('提前还款成功')
      this.$emit('success')
      this.beforeClose()
    },
  },
}
</script>
<style lang="scss" scoped>
.accounting-progress {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 3px solid;
  padding-top: 15px;
  text-align: center;
  clip-path: polygon(0% 90%, 0% 0%, 100% 0%, 100% 90%);
}
.label-text {
  display: inline-block;
  min-width: 90px;
  color: gray;
}
.accounting-table {
  width: auto;
  flex: 1;
  > tbody tr td:nth-of-type(2n + 1) {
    color: gray;
  }
}
</style>
